package com.langerra.server.channel.impl;

import javax.cache.Cache;

import com.langerra.server.channel.NamedCounter;

public class JCacheCounter
		implements NamedCounter {

	final Cache cache;
	final String key;

	public JCacheCounter(
			Cache cache,
			String key) {
		this.cache = cache;
		this.key = key;
	}

	@Override
	public long get() {
		return (Long) cache.get(key);
	}

	@Override
	@SuppressWarnings("unchecked")
	public synchronized long getAndAdd(
			long delta) {

		Long value;
		synchronized (cache) {
			value = (Long) cache.put(key, (get() + delta));
		}

		return (value == null) ? 0L : value;
	}

	@Override
	public synchronized long getAndDecrement() {
		return getAndAdd(-1L);
	}

	@Override
	public synchronized long getAndIncrement() {
		return getAndAdd(+1L);
	}

	@Override
	@SuppressWarnings("unchecked")
	public synchronized long getAndSet(
			long value) {
		Long old;

		synchronized (cache) {
			old = (Long) cache.put(key, Long.valueOf(value));
		}

		return (old == null) ? 0L : value;
	}
}
